<?php

namespace app\controllers\wx\services;

use app\models\system\SetWx;
use app\models\wx\WxAccessToken;
use app\util\Request;
use Yii;

class Wx
{
    // wx prefix
    protected static $apiPrefix = 'https://api.weixin.qq.com/';

    /**
     * get wx jsapi ticket
     *
     * @return mixed
     */
    public static function getJsapiTicket()
    {
        $cache = Yii::$app->cache;
        $cache_key = 'wx_js_ticket';
        $ticket = $cache->get($cache_key);

        if (!$ticket) {
            $url = sprintf('cgi-bin/ticket/getticket?access_token=%s&type=jsapi', self::getAccessToken());
            $url = self::$apiPrefix . $url;

            $response = Request::get($url);
            $result = json_decode($response, true);

            if (isset($result['ticket'])) {
                $ticket = $result['ticket'];
                $cache->set($cache_key, $ticket, $result['expires_in'] - 200);
            }
        }

        return $ticket;
    }

    /**
     * get wx access token
     */
    public static function getAccessToken()
    {
        // 1) exist not expired access token
        $now = date('Y-m-d H:i:s');
        $access_token = WxAccessToken::find()
            ->where(['>', 'expired_time', $now])
            ->select(['access_token'])
            ->scalar();

        if ($access_token) {
            return $access_token;
        }

        // 2) request wx
        $wx = SetWx::getLastOne(false);
        $url = sprintf('cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s', $wx->app_id, $wx->app_secret);
        $url = self::$apiPrefix . $url;

        $response = Request::get($url);
        $result = json_decode($response, true);

        if (isset($result['access_token'])) {
            $model = new WxAccessToken();
            $model->access_token = $result['access_token'];
            $model->expired_time = date('Y-m-d H:i:s', $result['expires_in'] + time() - 200);
            $model->created_time = $now;
            if ($model->save()) {
                return $model->access_token;
            }
        }
    }
}